module main

import log
import sync
import time
import encoding.utf8
import prantlf.cargs
import lib.ifaddrs
import lib.icmps

const usage = '...

Options:
  -l|--level <name>  log level
  -i|--interface_name <name> network interface name
  -t|--timeout ping timeout check
  -r|--retries ping failure retries
...'

struct Opts {
mut:
	level          string = 'info'
	interface_name string = 'wlp3s0'
	internal       int    = 4
	retries        int    = 5
}

fn ping_gateway(mut wg sync.WaitGroup, c chan bool, e chan bool, gw_addr string, internal int, retries int) {
	mut errs := 0
	mut diff := i64(0)
	mut done := false
	for {
		select {
			_ := <-e {
				done = true
				break
			}
			(internal * 1000 - diff) * time.millisecond {
				start := time.now()
				ok, str := icmps.ping(gw_addr, 1)
				diff = time.since(start).milliseconds()

				log.info(str)
				if ok {
					errs = 0
				} else {
					errs++
					if errs > retries {
						c <- true
					}
				}
			}
		}
		if done {
			break
		}
	}
	wg.done()
	log.info('ping_gateway done')
}

fn switch_network(mut wg sync.WaitGroup, c chan bool, e chan bool) {
	mut x := false
	for {
		select {
			n := <-c {
				if n { // 关闭
					println('a')
				} else { //打开
					println('b')
				}
			}
			_ := <-e {
				x = true
				break
			}
		}
		if x {
			break
		}
	}
	wg.done()
	log.info('switch_network done')
}

fn main() {
	mut opts, _ := cargs.parse[Opts](usage, cargs.Input{ version: '1.0.0' })!
	mut level := log.Level.info
	level = log.level_from_tag(utf8.to_upper(opts.level))?
	log.set_level(level)
	log.info('log[${opts.level}] init ok')

	gw_addr := ifaddrs.get_interface_gateway_address(opts.interface_name) or {
		log.error('no gateway address')
		return
	}
	log.info('gateway address:${gw_addr}')

	mut wg := sync.new_waitgroup()
	c := chan bool{}
	e := chan bool{}

	wg.add(1)
	spawn ping_gateway(mut wg, c, e, gw_addr, opts.internal, opts.retries)
	wg.add(1)
	spawn switch_network(mut wg, c, e)
	wg.wait()
	log.info('done')
}
